import time
import rand

import vcp.altmain
import vcp.sched
import vcp.mlog
import vcp.futex
import vcp.chan1

fn proc_send(chx voidptr) {
    mut stat := &Statistic(chx)
    mut ch := &stat.ch
    mlog.info(@FILE, @LINE, "send", chx)

    mut val := 500
    for {
        val ++
        rv := val
        ch.send(rv)
        stat.sndcnt++
        //time.sleep_ms(100)
    }
}

fn proc_recv(chx voidptr) {
    mut stat := &Statistic(chx)
    mut ch := &stat.ch
    mlog.info(@FILE, @LINE, "recv", chx)

    for {
        rv := 123
        ch.recv1(&rv)
        stat.rcvcnt++
        //mlog.info(@FILE, @LINE, "got", rv)
    }
}

fn donothing(mu &futex.Mutex) {
    mu.mlock()
    mu.munlock()
}
fn proc_callempty(chx voidptr) {
    mut stat := &Statistic(chx)
    mu := futex.newMutex()
    for {
        donothing(mu)
        stat.dntcnt ++
    }
}

struct Statistic {
    mut:
    ch chan1.Chan1
    sndcnt i64
    rcvcnt i64
    dntcnt i64
}

fn main() {
    mut stat := &Statistic{}
    ch := chan1.new<int>(30)
    stat.ch = ch
    println(C.GC_is_init_called())

    time.sleep(1)
    // sched.post(proc_recv, stat)
    //time.sleep(1)
    sched.post(proc_send, stat)
    // sched.post(proc_send, stat)

    time.sleep(1)
    sched.post(proc_recv, stat)

    //go proc_callempty(stat)

    mut sndcnt := i64(0)
    mut rcvcnt := i64(0)
    mut dntcnt := i64(0)
    for i := 0;; i++ {
        // time.sleep(5)
        ensuresleep(5)
        // 120w/s???
        mlog.info(@FILE, @LINE, "stat", stat.sndcnt, stat.rcvcnt, stat.dntcnt,
                  stat.sndcnt - sndcnt, stat.rcvcnt - rcvcnt, stat.dntcnt-dntcnt)
        sndcnt = stat.sndcnt
        rcvcnt = stat.rcvcnt
        dntcnt = stat.dntcnt

        if i == 10 {
            break
        }
    }
    mlog.info(@FILE, @LINE, "norm exit")
}

fn ensuresleep(n int) {
    btime := time.now()
    for {
        time.sleep(1)
        nowt := time.now()
        if nowt.unix_time() - btime.unix_time() >= n {
            break
        }
    }
}
